package client.comm.commlib.network

import client.comm.commlib.ContextProvider
import client.comm.commlib.utils.SharedUtil
import client.comm.commlib.utils.Util
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.IOException
import java.util.concurrent.TimeUnit
import javax.net.ssl.*
import java.net.Proxy
import java.security.KeyManagementException
import java.security.NoSuchAlgorithmException
import java.security.cert.X509Certificate
import javax.security.cert.CertificateException

class HhRetroHttp private constructor() {

    private val mRetrofit: Retrofit by lazy {
        val okHttpClient = OkHttpClient.Builder()
            .connectTimeout(50, TimeUnit.SECONDS) //5 7 7
            .writeTimeout(70, TimeUnit.SECONDS)
            .readTimeout(70, TimeUnit.SECONDS)
            .proxy(Proxy.NO_PROXY)
            .addInterceptor(object : Interceptor {
                @Throws(IOException::class)
                override fun intercept(chain: Interceptor.Chain): Response {

                    val ts = System.currentTimeMillis().toString() + ""
                    val token =
                        SharedUtil.read("token", "")
                    var version = 0

                    ContextProvider.get().activity?.let {
                        version = it
                            .packageManager
                            .getPackageInfo(it.packageName, 0).versionCode
                    }

                    //动态修改BaseUrl ***************************************

//                    // 匹配获得新的BaseUrl
//                    var newBaseUrl: HttpUrl? = null
//                    if (!SharedUtil.read(Constants.IS_ZEROHOST, "").isNullOrEmpty() ) {
//                        newBaseUrl = HH_URL_DEBUG.toHttpUrlOrNull()
//                        LogUtils.i("======" + 5001)
//                    } else {//默认
//                        newBaseUrl = BASE_URL.toHttpUrlOrNull()
//                        LogUtils.i("======" + 5000)
//                    }
//                    // 获取request
//                    val oldHttpUrl: HttpUrl = chain.request().url
//                    // 重建新的HttpUrl，修改需要修改的url部分
//                    val newFullUrl: HttpUrl = oldHttpUrl
//                        .newBuilder() // 更换网络协议
//                        .scheme(newBaseUrl!!.scheme) // 更换主机名
//                        .host(newBaseUrl.host) // 更换端口
//                        .port(newBaseUrl.port)
//                        .build()

                    val request: Request = chain.request().newBuilder()
                        .addHeader("access", "&OSpYVy#6g^Q7Fo#")
                        .addHeader("ts", ts)
                        .addHeader("database", "ll_mall")
                        .addHeader("version", "${version}")
                        .addHeader("sign", Util.getSign(ts))
                        .addHeader("token", "${token}")
//                        .url(newFullUrl)
                        .build()

                    return chain.proceed(request)


                }
            })
            .addInterceptor(HttpLoggingInterceptor().apply {
                level = HttpLoggingInterceptor.Level.BODY
            })
            //https支持
            .hostnameVerifier { hostname, session -> true }
            .sslSocketFactory(getSSLFactory(), initTrustManager())  //备用方案：initSSLSocketFactory()替代getSSLFactory()

        /*.sslSocketFactory(SSLSocketClient.getSSLSocketFactory())//配置
        .hostnameVerifier(SSLSocketClient.getHostnameVerifier())//配置*/
        /*//.hostnameVerifier(HostnameVerifier { hostname, session -> true })
        .hostnameVerifier(object : HostnameVerifier {
            override fun verify(hostname: String, session: SSLSession): Boolean {
                return true
            }
        })
    //实现SSLSocketFactory ，实现对TLSv1.1、TLSv1.2的支持
    //单向认证 客户端对服务端证书的单向认证？什么意思？
    if (AppParams.isBypassAuthen) {
        val sslParams: HttpsUtils.SSLParams = HttpsUtils.getSslSocketFactory(null, null, null)
        okHttpClient.sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
    } else {
        var sslContext: SSLContext? = null
        try {
            sslContext = SSLContext.getInstance("TLS")
            try {
                sslContext.init(null, null, null)
            } catch (e: KeyManagementException) {
                e.printStackTrace()
            }
        } catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
        }
        val socketFactory: SSLSocketFactory = Tls12SocketFactory(sslContext!!.getSocketFactory())
        okHttpClient.sslSocketFactory(socketFactory, HttpsUtils.UnSafeTrustManager())
    }*/
        var builder = okHttpClient.build()

        Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .client(builder)
            .build()
    }

//    var newHttpUrl = "http://120.77.64.128:5000/"

    companion object {
//        val BASE_URL = "http://1.94.60.6/"
        val BASE_URL = "http://app.yidabang.cn"       //易帮达正式端口
        //易帮达正式端口
//        val BASE_URL = "http://192.168.0.104:5000/"      //本地端口
//        val BASE_URL = "http://192.168.0.66:5000/"      //本地端口
//        val AGREEMENT = "https://mall.sd369sw.com/d/bd_agreement.html"//隐私政策

        private val INSTANT: HhRetroHttp by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { HhRetroHttp() }

        fun get(): HhRetroHttp {
            return INSTANT
        }

        fun <T> createApi(tClass: Class<T>): T {
            return lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { get().mRetrofit.create(tClass) }.value
        }
    }


    private fun getSSLFactory(): SSLSocketFactory {
        //证书忽略添加下面代码（1）打开即可
//         Create a trust manager that does not validate certificate chains
        val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
            override fun getAcceptedIssuers(): Array<out X509Certificate>? {
                return arrayOf()
            }

            @Throws(CertificateException::class)
            override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {
            }

            @Throws(CertificateException::class)
            override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {
            }
        })

        // Install the all-trusting trust manager
        val sslContext = SSLContext.getInstance("SSL")
        sslContext.init(null, trustAllCerts, java.security.SecureRandom())
        // Create an ssl socket factory with our all-trusting manager
        return sslContext.socketFactory
    }

//    private fun initSSLSocketFactory(): SSLSocketFactory {
//        var sslContext: SSLContext? = null
//        try {
//            sslContext = SSLContext.getInstance("SSL")
//            val xTrustArray = arrayOf(initTrustManager())
//            sslContext.init(
//                null,
//                xTrustArray, SecureRandom()
//            )
//        } catch (e: Exception) {
//            e.printStackTrace()
//        }
//        return sslContext!!.socketFactory
//    }

    private fun initTrustManager(): X509TrustManager {
        return object : X509TrustManager {

            override fun getAcceptedIssuers(): Array<out X509Certificate>? {
                return arrayOf()
            }

            override fun checkClientTrusted(chain: Array<X509Certificate>?, authType: String?) {
            }

            override fun checkServerTrusted(chain: Array<X509Certificate>?, authType: String?) {
            }

        }
    }


}

